//
//  ELUserAccount.swift
//  SinaWeiBo
//
//  Created by jiwang on 15/12/19.
//  Copyright © 2015年 jiwang. All rights reserved.
//

import UIKit

class ELUserAccount: NSObject , NSCoding {

    //MARK: -私有属性
    var access_token : String?
    
    //过期时间
    var expires_in : NSTimeInterval = 0 {
        didSet {
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var uid : String?
    ///过期时间
    var expires_Date : NSDate?
    ///用户昵称
    var screen_name: String?
    //头像地址
    var avatar_large: String?
    
    ///类属性:是否有登陆信息
    class var hasUserInfo : Bool {
        
        //有值返回tru
        return ELUserAccount.loadUserAccount() != nil
    }
    
    
    //MARK: - 构造方法
    init(dict:[String : AnyObject]) {
        
        super.init()
        //字典转模型
        self.setValuesForKeysWithDictionary(dict)
        
    }
    //覆盖父类 找不到字典属性不报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //MARK: - 私有方法
    ///读取用户信息
    func loadingUserInfo (finished: (error: NSError?) -> ()) {
        ELNetWorkTool.shareNetWork.loadUserInfo { (result, error) -> () in
            
            //有错误则返回
            if error != nil {
                finished(error: error)
                return
            }
            
            //有值则保存
            self.avatar_large = result!["avatar_large"] as? String
            self.screen_name = result!["screen_name"] as? String
            
            self.saveUserAccount()
            ELUserAccount.userAccount = self
            
            finished(error: nil)
        }
    }
    
    ///打印对象内容
    override var description: String {
        get {
            return "access_token: \(access_token), uid: \(uid), expires_in: \(expires_in), expires_Date: \(expires_Date)"
        }
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    ///归档路径
    private static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    func saveUserAccount () {
        //访问静态变量要添加类名
        NSKeyedArchiver.archiveRootObject(self, toFile: ELUserAccount.path)
    }
    
    static  var userAccount : ELUserAccount?
    
    class func loadUserAccount () -> ELUserAccount? {
        
        //因为要多次调用 所以首先读取内存中是否有用户信息
        if userAccount == nil {
            //如果没有 读取沙盒
//            print("读取沙盒数据")
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ELUserAccount
        }
        
        //如果沙盒有且没有过期
        if userAccount != nil && userAccount!.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//            print("有账户可用，使用缓存")
            return userAccount
        }
        
//        print("没有账户或者已经过期")
        return nil
    }

//    class func loadUserAccount () -> ELUserAccount? {
//        
//        //解档，读取用户信息
//        if let userAcount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ELUserAccount {
//            
//            //账户保存的过期日期 r如果大于 descend：降序 则表示账户可以
//            if userAcount.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//                
//                print("加载的账户可用")
//                return userAcount
//                
//            }else {
//                
//                print("账户过期")
//                return nil
//            }
//            
//        }else {
//            print("没有加载到账号")
//        }
//        
//        return nil
//    }
}
